$(document).ready(function(){
 	// 路径配置
 	    require.config({
 	        paths: {echarts: 'dist/js'},
 	        packages: [{name: 'BMap',location: 'dist/js/BMap', main: 'main'}
 	                  
 	                 ]
 	    });
 		$("#search_btn").click(btn_clickloadBmap);

 	});
 	$(window).load(function(){
 		universalPreloaderRemove2();
 	});	
 	
 	var option={};
 	var myChart=null;
 	var BMapExt=null;
 	/**
 	 * 
 	 * @param option 
 	 * @param line2 连线
 	 * @param d_info 标注点
 	 */
 	function initMyechart(option,line2,d_info){
	    require(['echarts','BMap', 'echarts/chart/map'], 
	    		function(echarts, BMapExtension){
	    	//alert("a");
	    	$('#main').css({
	            height:$('body').height(),
	            width: $('body').width()
	        });
	        // 初始化地图
	    	
	        BMapExt = new BMapExtension($('#main')[0], BMap, echarts);
	        var map = BMapExt.getMap();

	        var startPoint = {
	            x: 100.3467,
	            y: 41.4899
	        };
	        var point = new BMap.Point(startPoint.x, startPoint.y);
	        map.centerAndZoom(point, 5);
	        //map.setCurrentCity("中国");
	        map.enableScrollWheelZoom(true);//启用滚轮放大
	        map.disableDoubleClickZoom(true);//禁止双击放大
//	        var b = new BMap.Bounds(new BMap.Point(81.9379510000,175.1126230000),new BMap.Point(-78.8050600000,-150.5068820000));
//	    	try {	
//	    		BMapLib.AreaRestriction.setBounds(map, b);
//	    	} catch (e) {
//	    		alert(e);
//	    	}
	        map.setMapStyle({//样式固定
	        	//style : "dark"
	        	styleJson:[{"featureType":"land","elementType":"geometry","stylers":{"color":"#212121"}},
	        	           {"featureType":"building","elementType":"geometry","stylers":{"color":"#2b2b2b"}},
	        	           {"featureType":"highway","elementType":"all","stylers":{"color":"#313131","lightness":-42,"saturation":-91}},
	        	           {"featureType":"arterial","elementType":"geometry","stylers":{"lightness":-77,"saturation":-94}},
	        	           {"featureType":"green","elementType":"geometry","stylers":{"color":"#1b1b1b"}},
	        	           {"featureType":"water","elementType":"geometry","stylers":{"color":"#181818"}},
	        	           {"featureType":"subway","elementType":"geometry.stroke","stylers":{"color":"#181818"}},
	        	           {"featureType":"railway","elementType":"geometry","stylers":{"lightness":-52}},
	        	           {"featureType":"all","elementType":"labels.text.stroke","stylers":{"color":"#313131"}},
	        	           {"featureType":"all","elementType":"labels.text.fill","stylers":{"color":"#8b8787"}},
	        	           {"featureType":"manmade","elementType":"geometry","stylers":{"color":"#1b1b1b"}},
	        	           {"featureType":"local","elementType":"geometry","stylers":{"lightness":-75,"saturation":-91}},
	        	           {"featureType":"subway","elementType":"geometry","stylers":{"lightness":-65}},
	        	           {"featureType":"railway","elementType":"all","stylers":{"color":"#252525","lightness":-40}},
	        	           {"featureType":"boundary","elementType":"geometry","stylers":{"color":"#8b8787","weight":"1","lightness":-29}},
	        	           {"featureType":"background","elementType": "all","stylers": {"color": "#000000"}}
	        	          ]
	        });
	        var container = BMapExt.getEchartsContainer();
	        myChart = BMapExt.initECharts(container);
	        window.onresize = myChart.resize;
	        if(line2!=null&&d_info!=null&&option!=null){
	        	var map = BMapExt.getMap();
			    //map.clearOverlays();//清除所有标注
			    var cc=0;
			    for(var kk in d_info){
			    	if(cc==0){
			    		var point = new BMap.Point(d_info[kk][0],d_info[kk][1]);
					    map.centerAndZoom(point, 5);
			    	}
			    	//console.log(kk+":"+d_info[kk][0]+","+d_info[kk][1]);
			    	addPointM(d_info[kk],map,cc);
			    	cc++;
				}
			    BMapExt.setOption(option);
			    if(line2.length>0){
		        	var x= 0;
	 				var line=[line2[0]];
	 				interval_id=setInterval(function(){
	 					x++;
	 					if(x==line2.length){ 
	 						clearInterval(interval_id);
	 						option.series[0].markLine.data=line;
	 						//BMapExt.setOption(option);
	 						//option['animation']=false;
	 						BMapExt.setOption(option);
	 						return ;
	 					}
	 					line.push(line2[x]);
	 					option.series[0].markLine.data=[line2[x]];
	 					BMapExt.setOption(option);
	 				},2000);
	 				
		        }
	        }else{
 	        	option = {tooltip:{trigger: 'item',formatter: '{b0}',},color:['#0af','#0af'],animationDurationUpdate:5000,
 							series : [{name:"aaa", type:'map', mapType: 'none',hoverable:false,data:[]}]
 		 	        };
 	        	BMapExt.setOption(option);
	        }
	         
	    });
    }
 	
    var interval_id=null;
    function btn_clickloadBmap(){
 			if($("#inp_search").val()==null||$("#inp_search").val()==""){
 				alert("搜索内容不可为空");return ;
 			}

 			var submitURl="";
 			//var data=$("#inp_search").closest('form').serializeArray();
 			//暂时性辨别邮箱
 			var out1="tang2007@163.com";
 			var out2="pkpk3322@163.com";
 			var out3="lalt_ralt@yahoo.com.cn";
 			var emailtemp=$("#inp_search").val();
 			if(out1.indexOf(emailtemp) >=0){
 				submitURl="out.json";
 			}else if(out2.indexOf(emailtemp) >=0){
 				submitURl="out2.json";
 			}else if(out3.indexOf(emailtemp) >= 0){
 				submitURl="out3.json";
 			}else{
 				alert("没有结果");
 				return ;
 			}
 			if(interval_id!=null) clearInterval(interval_id);
 			
 			if(myChart==null){
 				initMyechart(null,null,null);//初始化
 			}else{
 				myChart.dispose();  //暂时调试用clear  使用是用 dispose
 			}
 			
 			option={};
 			var geoCoord={};//标注点
 			var make=[];//标注点
 			var d_info ={};//标注提示信息
 			var line2=[];//连线
 			jQuery.get(submitURl,null,function(jsonData){
 				if(jsonData['code']==0){
 					var data=jsonData.data;
 					var tempLine=[];
 					var tempName=null;
 					var temppass="";
 					var tempdata_item=[];
 					var Begin_city;
 					for(var i in data){
 						console.log(data[i]);
 						if(data[i]['reg_ip_geo']['city']==null){ //判断为空reg_time
 							data[i]['reg_ip_geo']['city']=data[i].reg_time;
 						}
 						if(geoCoord[data[i].reg_ip_geo['city']]==null){//没重复
 							if(jsonData.base_info[''+(parseInt(i)+1)].password!=null){
 								temppass=jsonData.base_info[(parseInt(i)+1)+""].password;
 							}
 							if(i==0){//为第一个点加用户详细信息
 								var countent = [];
 								Begin_city=data[i].reg_ip_geo['city'];
 								if(jsonData.user_info[(parseInt(i)+1)+""].realname!=null)
 									countent.push("姓名："+jsonData.user_info[(parseInt(i)+1)+""].realname);
 								if(jsonData.user_info[(parseInt(i)+1)+""].phone!=null)
 									countent.push("手机："+jsonData.user_info[(parseInt(i)+1)+""].phone);
 								if(jsonData.user_info[(parseInt(i)+1)+""].email!=null)
 									countent.push("邮箱："+jsonData.user_info[(parseInt(i)+1)+""].email);
 								countent.push("密码："+temppass);
 								if(jsonData.user_info[(parseInt(i)+1)+""].qq!=null)
 									countent.push("QQ："+jsonData.user_info[(parseInt(i)+1)+""].qq);
 								if(jsonData.user_info[(parseInt(i)+1)+""].birthday!=null)
 									countent.push("生日："+new Date(parseInt(jsonData.user_info[(parseInt(i)+1)+""].birthday) * 1000).format("yyyy年MM月dd日"));
 								if(jsonData.user_info[(parseInt(i)+1)+""].political_status!=null)
 									countent.push("政治面貌："+jsonData.user_info[(parseInt(i)+1)+""].political_status);
 								if(jsonData.user_info[(parseInt(i)+1)+""].old_school!=null)
 									countent.push("学校："+jsonData.user_info[(parseInt(i)+1)+""].old_school);
 								if(jsonData.user_info[(parseInt(i)+1)+""].address!=null)
 									countent.push("住址："+jsonData.user_info[(parseInt(i)+1)+""].address);
 								tempdata_item.push(data[i].reg_ip_geo['loc'][0]);
 								tempdata_item.push(data[i].reg_ip_geo['loc'][1]);
 								tempdata_item.push(countent.join("<br>"));
 								//tempdata_item.push(new Date(parseInt(data[i].reg_time) * 1000).toLocaleString().substr(0,16));
 								tempdata_item.push(new Date(parseInt(data[i].reg_time) * 1000).format("yyyy年MM月"));
 								
 							} else{
 								var countent = [];
 								if(jsonData.base_info[(parseInt(i)+1)+""].user_name!=null)
 									countent.push("用户名："+jsonData.base_info[(parseInt(i)+1)+""].user_name);
 								if(jsonData.base_info[(parseInt(i)+1)+""].email!=null)
 									countent.push("邮箱："+jsonData.base_info[(parseInt(i)+1)+""].email);
 								countent.push("密码："+temppass);
 								tempdata_item.push(data[i].reg_ip_geo['loc'][0]);
 								tempdata_item.push(data[i].reg_ip_geo['loc'][1]);
 								tempdata_item.push(countent.join("<br>"));
 								//tempdata_item.push(new Date(parseInt(parseInt(data[i].reg_time)) * 1000).toLocaleString().substr(0,16));
 								tempdata_item.push(new Date(parseInt(data[i].reg_time) * 1000).format("yyyy年MM月"));
 							}
 							d_info[data[i].reg_ip_geo['city']]=tempdata_item;
 							//alert(d_info[data[i].reg_ip_geo['city']][0]+","+d_info[data[i].reg_ip_geo['city']][1]+","+d_info[data[i].reg_ip_geo['city']][2]+",")
 		 					tempdata_item=[];
 							geoCoord[data[i].reg_ip_geo['city']]=data[i].reg_ip_geo['loc'];
// 							make.push(data[i].reg_ip_geo['loc']);
 						}else{ //重复  替换 d_info 的值为新值
 							var repeatd_info=d_info[data[i].reg_ip_geo['city']];
 							//console.log("重复城市名"+data[i].reg_ip_geo['city']+"序号："+i+repeatd_info[0]+","+repeatd_info[1]+","+repeatd_info[2]+",");
 							var tempcount=repeatd_info[2];
 							var temptitle=repeatd_info[3];
 							d_info[data[i].reg_ip_geo['city']][3]=new Date(parseInt(data[i].reg_time) * 1000).format("yyyy年MM月");
 							if(Begin_city==data[i].reg_ip_geo['city']){//如果是第一个点 则继续增加信息
							var countent = tempcount.split("<br>");
							
							countent.push("<span style='color: #ccc;'>"+temptitle+"</span>");//小标题
							
							if(jsonData.base_info[(parseInt(i)+1)+""].user_name!=null)
								countent.push("用户名："+jsonData.base_info[(parseInt(i)+1)+""].user_name);
							if(jsonData.base_info[(parseInt(i)+1)+""].email!=null)
								countent.push("邮箱："+jsonData.base_info[(parseInt(i)+1)+""].email);
							countent.push("密码："+jsonData.base_info[(parseInt(i)+1)+""].password);
							d_info[data[i].reg_ip_geo['city']][2]=countent.join("<br>");
 								//tempcount+="<br>"+;
 							}else{//后续历史点 则覆盖信息
 								var countent = [];
 								if(jsonData.base_info[(parseInt(i)+1)+""].user_name!=null)
 									countent.push("用户名："+jsonData.base_info[(parseInt(i)+1)+""].user_name);
 								if(jsonData.base_info[(parseInt(i)+1)+""].email!=null)
 									countent.push("邮箱："+jsonData.base_info[(parseInt(i)+1)+""].email);
 								countent.push("密码："+jsonData.base_info[(parseInt(i)+1)+""].password);
 								d_info[data[i].reg_ip_geo['city']][2]=countent.join("<br>");
 							}
 							
 						}
 						if(tempLine.length==0){
 	 						tempLine.push({name:data[i].reg_ip_geo['city'],value:90});
	 					}else if(tempLine.length==1){
 							if(tempLine[0].name!=data[i].reg_ip_geo['city']){
 	 	 						tempLine.push({name:data[i].reg_ip_geo['city'],value:90});
 							}
	 					}
	 					if(tempLine.length==2) {
							line2.push(tempLine);
							tempLine=[];
							tempLine.push({name:data[i].reg_ip_geo['city'],value:90});
	 					}
 					}
 					var linet=[];
 					if(line2.length>0) linet=[line2[0]];
 					option = {
 							tooltip:{trigger: 'item',formatter: '{b0}',},color:['#0af','#0af'],animationDurationUpdate:5000,//animation:false,
 							series : [{name:"aaa", type:'map', mapType: 'none',hoverable:false,data:[],geoCoord:geoCoord,
		 		 	                   markLine:{smooth:true,effect:{show:true,loop:false,scaleSize:1,period:30,color:'#fff',shadowBlur:0},
		 		 	                   itemStyle:{normal:{borderWidth:1,label:{show:false},lineStyle:{type:'solid',shadowBlur:10}}}, 
		 		 	                   data : linet}}
		 		 	                 ]
 		 	        };
 					
 					initMyechart(option,line2,d_info);
	 				
 				}
     		},'json');
    }
    
    function addPointM(data,map,index){
        point_d=new BMap.Point(data[0],data[1]);
        var myIcon = new BMap.Icon("dist/img/blue.png",  new BMap.Size(23, 23));
        
      	var marker = new BMap.Marker(point_d,{icon:myIcon});  // 创建标注
    	map.addOverlay(marker);               // 将标注添加到地图中
    	marker.setAnimation(BMAP_ANIMATION_BOUNCE); //跳动的动画
    	
    	
    	var myCompOverlay=new ComplexCustomOverlay(point_d, data[2], data[3],index); //这步是将覆盖物存到变量，以便下面使用。
    	map.addOverlay(myCompOverlay);
    	
    	addClickHandler(data[2],data[3],marker,index);
 	}
 	function addClickHandler(content,title,marker,index){

		marker.addEventListener("click",function(e){
//	    	var map = this._map;
//	    	var pixel = map.pointToOverlayPixel(this._point);
//	    	this._div.style.left = pixel.x+30 + "px";//+this._div.offsetWidth
//	    	this._div.style.top = pixel.y -this._div.offsetHeight/2+ "px";//+
			var div_obj=$("#pop-dialog_"+index);
			//var offset = div_obj.offset();
			//div_obj.css({top:offset.top-div_obj.heigh()+"px"});
			div_obj.slideToggle();
			$("body").bind("mousedown",{id:"#pop-dialog_"+index}, onBodyDown);
		 }
		);
	}
	function openInfo(content,title,e,map){
		var p = e.target;
		var point = new BMap.Point(p.getPosition().lng, p.getPosition().lat);
		var opts = {
        		  width : 280,     // 信息窗口宽度
        		  height: 100,     // 信息窗口高度
        		  title : title , // 信息窗口标题
        		  enableMessage:false,//设置允许信息窗发送短息
        		  enableAutoPan:true
        		}//overflow-y:scroll;
		var infoWindow = new BMap.InfoWindow("<p style='font-size:12px;lineheight:1.8em;'>"+content+"</p>",opts);  // 创建信息窗口对象 
		map.openInfoWindow(infoWindow,point); //开启信息窗口
	}
    function ComplexCustomOverlay(point, text, title,index){
    	this._point = point;
    	this._text = text;
    	this._title = title;
    	this._idseq=index;
    }
    ComplexCustomOverlay.prototype = new BMap.Overlay();
    ComplexCustomOverlay.prototype.initialize = function(map){
    	
    	this._map = map;
    	var div =this._div = document.createElement("div");
    	//<button type="button" class="close" >×</button>
    	var $div=$(div);
    	$div.attr("id","pop-dialog_"+this._idseq);
    	$div.addClass("pop-dialog");
    	var button_obj=$("<button type='button' class='close' onclick=\"hideMenu('#pop-dialog_"+this._idseq+"')\""+"'>×</button>").appendTo($div);// 
    	//button_obj.click(function(){
    		//$("#pop-dialog_"+this._idseq).fadeOut("fast");
    	//});
    	var body_div =$("<div class='body'>").appendTo($div);//+this._text+
    	//if()//color: #0af;
    	$("<div class='map_tip_head'>"+this._title+"<div>").appendTo(body_div);
    	$("<div class='map_tip_counten'>"+this._text+"<div>").appendTo(body_div);
    	
    	div=$div.get(0);
    	
    	map.getPanes().labelPane.appendChild(div);
    	return div;
    }
    ComplexCustomOverlay.prototype.draw = function(){
    	var map = this._map;
    	var pixel = map.pointToOverlayPixel(this._point);
    	this._div.style.left = pixel.x+30 + "px";//+this._div.offsetWidth
    	this._div.style.top = pixel.y -this._div.offsetHeight/2+ "px";//+
    }
    ComplexCustomOverlay.prototype.addEventListener = function(event,fun){
    	this._div['on'+event] = fun;
    }
	  
    
    
    
    
  //时间格式化
 	Date.prototype.format = function(format){ 
 		var o = { 
 		"M+" : this.getMonth()+1, //month 
 		"d+" : this.getDate(), //day 
 		"h+" : this.getHours(), //hour 
 		"m+" : this.getMinutes(), //minute 
 		"s+" : this.getSeconds(), //second 
 		"q+" : Math.floor((this.getMonth()+3)/3), //quarter 
 		"S" : this.getMilliseconds() //millisecond 
 		} 

 		if(/(y+)/.test(format)) { 
 		format = format.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
 		} 

 		for(var k in o) { 
 		if(new RegExp("("+ k +")").test(format)) { 
 		format = format.replace(RegExp.$1, RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length)); 
 		} 
 		} 
 		return format; 
 	}
 	/**
 	 * 获取url 参数
 	 */
 	function getQueryString(name) { 
		var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); 
		var r = window.location.search.substr(1).match(reg); 
		// location = encodeURI(encodeURI(url));
		if (r != null) return unescape(r[2]);; return null; 
		} 
 	/**
 	 * 初始化加载动画
 	 */
 	function universalPreloaderRemove2(){
 		var parentD = $("#universal-preloader");
 		var pre = $("#universal-preloader>div");
 		
		initMyechart(null,null,null);
 		pre.delay(500).animate({opacity:'0'},{duration:400, complete:function(){
 			parentD.animate({opacity:'0'},{duration:400, complete:function(){
 				parentD.remove();
 			    var keyword = getQueryString('user_name');
 		 	    if(keyword == null){
 					keyword =''; 
 				}else{
 					keyword = decodeURI(decodeURI(keyword));
 				    $("#inp_search").val(keyword);
 				    btn_clickloadBmap();
 				}
 			}});
 		}});
 		
 	}
	    //原搜索弹出模糊狂
//			var target=$("#user_item");
//			target.empty();
//			if(jsonData.length>0){
//				for(var item in jsonData) {
//					$("<a href='#"+jsonData[item].user_account+"' class='list-group-item'>"+jsonData[item].user_account+"</a>").appendTo(target);
//				}
//				target.find("a").bind("click",loaduserhistory)
//				$("#user_modal").modal('show');
//			}else{
//				//没有查询结果
//				
//			}
	    
	    
	    //原搜索弹出模糊点击get
//			var num= Math.round(Math.random()*99+1);
//			var count=0;
//			var line= new Array();
//			for(var item in obj){
//				count++;
//				if(count-2<=num&&count>=num){//取随机数的后3个
//					geoCoord[item]=obj[item];
//					
//				}
//				break;
//			}
    
    
    
    //添加线到地图 百度api  	<script type="text/javascript" src="http://api.map.baidu.com/library/CurveLine/1.5/src/CurveLine.min.js"></script>
//        var beijingPosition=new BMap.Point(116.432045,39.910683),
//			hangzhouPosition=new BMap.Point(120.129721,30.314429),
//			taiwanPosition=new BMap.Point(121.491121,25.127053);
// 		var points = [beijingPosition,hangzhouPosition, taiwanPosition];
//
// 		var curve = new BMapLib.CurveLine(points, {strokeColor:"blue", strokeWeight:3, strokeOpacity:0.5}); //创建弧线对象
// 		map.addOverlay(curve); //添加到地图中
//        //添加点到地图中
	
	
	
	  //map.enableKeyboard(true);//键盘移动 goole 不支持
    //map.addControl(new BMap.ScaleControl()); // 添加默认比例尺控件
    //map.addControl(new BMap.ScaleControl({anchor: BMAP_ANCHOR_BOTTOM_LEFT})); // 左下
    //map.addControl(new BMap.NavigationControl()); //添加默认缩放平移控件
    //map.addControl(new BMap.NavigationControl({anchor: BMAP_ANCHOR_TOP_right, type: BMAP_NAVIGATION_CONTROL_SMALL})); //右上角，仅包含平移和缩放按钮